using System;
using System.Drawing;
using System.Windows.Forms;

namespace Shrapnel
{
    internal class SelectionRectangle
    {
        /// <summary>
        /// The starting location of the selection rectangle, in world space
        /// </summary>
		private PointF startLocation = PointF.Empty;

        /// <summary>
        /// The current location of the mouse.
        /// </summary>
		private PointF location = PointF.Empty;


		/// <summary>
		/// Gets or sets the starting location of the selection rectangle.
		/// </summary>
		public PointF StartLocation
		{
			set { startLocation = value; }
			get { return startLocation; }
		}

        /// <summary>
        /// Gets or sets the current location of the mouse.
        /// </summary>
		public PointF Location
        {
            set { location = value; }
            get { return location; }
        }

        /// <summary>
        /// Draws the selection rectangle to the screen.
        /// </summary>
        /// <param name="e">The paint event arguments used to draw.</param>
        public void Draw(PaintEventArgs e, ViewState view)
        {
            RectangleF rectangle = RectangleF.Empty;

			PointF screenStart = view.WorldToScreen(startLocation);
			PointF screenEnd = view.WorldToScreen(location);

            rectangle.Location = new PointF(
					Math.Min(screenEnd.X, screenStart.X),
					Math.Min(screenEnd.Y, screenStart.Y)
                );

            rectangle.Size = new SizeF(
					Math.Abs(screenEnd.X - screenStart.X),
					Math.Abs(screenEnd.Y - screenStart.Y)
                );

            using (SolidBrush brush = new SolidBrush(Color.FromArgb(128, 255, 255, 128)))
            {
                e.Graphics.DrawRectangle(Pens.DarkGray, rectangle.X - 1, rectangle.Y - 1, rectangle.Width + 1, rectangle.Height + 1);
                e.Graphics.FillRectangle(brush, rectangle);
            }
        }


		/// <summary>
		/// Get the selection rectangle's box as a world space bounding box.
		/// </summary>
		/// <param name="viewState">The view to use for determining the worldspace coordinates</param>
		/// <returns>A bounding box</returns>
		public BoundingBox GetWorldSelectionBox()
		{
			PointF topLeft = new PointF(
				Math.Min(startLocation.X, location.X),
				Math.Min(startLocation.Y, location.Y));

			// We add 1 pixel on the right and bottom, since we want our bottomRight location to be included
			// in the box too.
			SizeF size = new SizeF(
				Math.Abs(startLocation.X - location.X) + 1.0f,
				Math.Abs(startLocation.Y - location.Y) + 1.0f);

			return new BoundingBox(topLeft, size);
		}
    }
}
